package com.javaframe.role.web;

import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.apache.commons.beanutils.BeanUtils;

import com.javaframe.role.entity.Role;
import com.javaframe.role.service.RoleService;
import com.javaframe.role.tools.ConditionInfo;
import com.javaframe.role.tools.GenericsUtils;
import com.javaframe.role.tools.PageInfo;




@Controller
public class RoleController {

	RoleService service;
	
	@Autowired
	public void setRoleService(RoleService roleService) {
		this.service = roleService;
	}

	@RequestMapping(method=RequestMethod.POST, value="/roles")
	@ResponseBody
	public Map<String, Object> getRoles(@RequestBody ModelMap map){
		List<ConditionInfo> listCondition = GenericsUtils.formatMultiFilter(map);
		PageInfo page=GenericsUtils.formatPageInfo(map);
		List<Role> users=service.findAll(listCondition,page);
		return GenericsUtils.formatResponseData(map,users,page,"roleId");
    }
	
	@RequestMapping(method=RequestMethod.POST, value="/role/create")
	@ResponseBody
	public void addRole(@RequestBody Map<String, Object> map) throws IllegalAccessException, InvocationTargetException{ 
		Role role = new Role();
		role.setDeleted(Short.valueOf("0"));
		BeanUtils.copyProperties(role, map);
		service.save(role);
    }
	
	@RequestMapping(method=RequestMethod.POST, value="/role/fetch/{id}")
	@ResponseBody
	public Role getRole(@PathVariable Integer id) throws IllegalAccessException, InvocationTargetException{ 
        return service.findById(id);
    }
	
	@RequestMapping(method=RequestMethod.POST, value="/role/update/{id}")
	@ResponseBody
	public void updateRole(@RequestBody Map<String, Object> map,@PathVariable Integer id) throws IllegalAccessException, InvocationTargetException{ 
		Role role=new Role();
		BeanUtils.copyProperties(role, map);
		service.save(role);
    }
	
	@RequestMapping(method=RequestMethod.POST, value="/role/delete")
	@ResponseBody
	public void deleteRole(@RequestBody Map<String, Object> map) throws IllegalAccessException, InvocationTargetException{ 
		map.put("table", "Role");
		map.put("identifier", "roleId");
		service.delete(map);
    }
}
